<template>
  <div id="app">
    <header>
      <h1>商品列表</h1>
    </header>
    <main class="main-container">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="分类" name="category">
          <div class="content">
            <div class="category-list">
              <div
                v-for="category in categories"
                :key="category.id"
                class="category-item"
                @click="fetchProducts(category.id)"
              >
                <h2>{{ category.name }}</h2>
                <p>{{ category.description }}</p>
              </div>
            </div>

            <div class="product-list">
              <div v-if="loading">加载中...</div>
              <div v-else-if="error">{{ error }}</div>
              <div v-else>
                <div class="product" v-for="product in products" :key="product.id">
                  <h2>{{ product.name }}</h2>
                  <p>价格: ¥{{ product.price }}</p>
                  <p>库存: {{ product.count }}</p>
                  <p>厂家: {{ product.manufacturer }}</p>
                  <p>描述: {{ product.description }}</p>

                  <!-- 选择数量和按钮 -->
                  <div class="quantity-selection">
                    <button @click="decreaseQuantity(product)" class="adjust-button">-</button>
                    <input
                      type="number"
                      id="quantity-{{ product.id }}"
                      v-model="product.selectedQuantity"
                      min="1"
                      max="product.count"
                      class="quantity-input"
                    />
                    <button @click="increaseQuantity(product)" class="adjust-button">+</button>
                    <div class="button-group">
                      <!-- <button @click="addToCart(product)" class="add-cart-button">加入购物车</button> -->
                    <button @click="buyProduct(product)" class="buy-button" 
                        :disabled="product.selectedQuantity <= 0 || product.selectedQuantity > product.count">
                        立即购买
                    </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="品牌" name="brand">
          <div class="content">
            <div class="category-list">
              <div class="brand-list">
                <div
                  v-for="brand in brands"
                  :key="brand.id"
                  class="category-item"
                  @click="fetchProductBrands(brand.id)"
                >
                  <h2>{{ brand.name }}</h2>
                  <p>{{ brand.description }}</p>
                </div>
              </div>
            </div>

            <div class="product-list">
              <div v-if="loading">加载中...</div>
              <div v-else-if="error">{{ error }}</div>
              <div v-else>
                <div class="product" v-for="product in products" :key="product.id">
                  <h2>{{ product.name }}</h2>
                  <p>价格: ¥{{ product.price }}</p>
                  <p>库存: {{ product.count }}</p>
                  <p>厂家: {{ product.manufacturer }}</p>
                  <p>描述: {{ product.description }}</p>

                  <!-- 选择数量和按钮 -->
                  <div class="quantity-selection">
                    <button @click="decreaseQuantity(product)" class="adjust-button">-</button>
                    <input
                      type="number"
                      id="quantity-{{ product.id }}"
                      v-model="product.selectedQuantity"
                      min="1"
                      max="product.count"
                      class="quantity-input"
                    />
                    <button @click="increaseQuantity(product)" class="adjust-button">+</button>
                    <div class="button-group">
                      <!-- <button @click="addToCart(product)" class="add-cart-button">加入购物车</button> -->
                      <button @click="buyProduct(product)" class="buy-button">立即购买</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElTabs, ElTabPane } from "element-plus";
import "element-plus/es/components/tabs/style/css";
import "element-plus/es/components/tab-pane/style/css";
import { useRouter } from 'vue-router';
import { get,post } from '@/utils/request';

const activeTab = ref("category");
const categories = ref([]);
const brands = ref([]);
const products = ref([]);
const loading = ref(true);
const error = ref(null);
const router = useRouter();

const fetchCategories = async () => {
  try {
    const response = await axios.get("http://127.0.0.1:8000/goods/category/");
    if (response.data.code === 200) {
      categories.value = response.data.data;
      if (categories.value.length > 0) {
        await fetchProducts(categories.value[0].id);
      }
    } else {
      error.value = "获取商品类别失败，请稍后重试。";
    }
  } catch (err) {
    error.value = "网络错误或服务器不可用。";
  }
};

const fetchBrands = async () => {
  try {
    const response = await axios.get("http://127.0.0.1:8000/goods/brand/");
    if (response.data.code === 200) {
      brands.value = response.data.data;
    } else {
      error.value = "获取品牌数据失败，请稍后重试。";
    }
  } catch (err) {
    error.value = "网络错误或服务器不可用。";
  }
};

const fetchProductBrands = async (brandId) => {
  loading.value = true;
  try {
    const response = await axios.get(`http://localhost:8000/goods/brands/${brandId}/`);
    if (response.data.code === 200) {
      products.value = response.data.data.map(product => ({
        ...product,
        selectedQuantity: 0 // 初始化选择数量
      }));
    } else {
      error.value = "未能获取商品数据";
    }
  } catch (err) {
    error.value = "加载失败，请重试。";
  } finally {
    loading.value = false;
  }
};

const fetchProducts = async (categoryId) => {
  loading.value = true;
  try {
    const response = await axios.get(`http://localhost:8000/goods/products/${categoryId}/`);
    if (response.data.code === 200) {
      products.value = response.data.data.map(product => ({
        ...product,
        selectedQuantity: 0 // 初始化选择数量
      }));
    } else {
      error.value = "未能获取商品数据";
    }
  } catch (err) {
    error.value = "加载失败，请重试。";
  } finally {
    loading.value = false;
  }
};

const buyProduct = async (product) => {
  const quantity = product.selectedQuantity;
  if (quantity > 0 && quantity <= product.count) {
    try {
      const response = await axios.post('http://127.0.0.1:8000/order/ordercreate/', {
        total_count: quantity,
        total_price: product.price, // 单价
        product_id: product.id,//选中的商品id
      });

      if (response.data.code === 200) {
        alert(`您成功购买了 ${quantity} 个 ${product.name}`);
        let order_id = response.data.order_id;
        // console.log(order_id);
        toAliPay(order_id);
      } else {
        alert('订单创建失败，请重试');
      }
    } catch (error) {
      console.error(error); // 打印错误以帮助调试
      alert('网络错误，请重试');
    }
  }
}
const toAliPay = (order_id) => {
  post('http://127.0.0.1:8000/order/pay/', {"orderId": order_id})
    .then((result) => {
      if (result.data.code == 200) {
        const url = result.data.url;
        window.location.href=url;
      }
    })
    .catch((err) => {
      console.error('请求失败:', err);
    });
}; 

const addToCart = (product) => {
  const quantity = product.selectedQuantity;
  if (quantity > 0 && quantity <= product.count) {
    // 在这里处理加入购物车的逻辑
    alert(`已将 ${quantity} 个 ${product.name} 加入购物车`);
  } else {
    alert("请选择有效的数量。");
  }
};

// 减少数量
const decreaseQuantity = (product) => {
  if (product.selectedQuantity > 1) {
    product.selectedQuantity--;
  }
};

// 增加数量
const increaseQuantity = (product) => {
  if (product.selectedQuantity < product.count) {
    product.selectedQuantity++;
  }
};

onMounted(async () => {
  await fetchCategories();
  await fetchBrands();
});
</script>

<style scoped>
/* 主容器样式 */
#app {
  font-family: Arial, sans-serif;
  padding: 2rem;
  background-color: #f7fafc;
  min-height: 100vh;
}

header {
  text-align: center;
  margin-bottom: 20px;
  color: #3498db;
}

.content {
  display: flex;
  gap: 2rem;
}

.category-list {
  width: 30%;
  overflow-y: hidden;
}

.product-list {
  width: 70%;
}

/* 卡片样式 */
.category-item,
.brand-item {
  background-color: #ffffff;
  padding: 1.5rem;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  text-align: left;
}

.category-item:hover,
.brand-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.category-item h2,
.brand-item h2 {
  font-size: 1.3rem;
  color: #333;
  margin-bottom: 0.5rem;
}

.category-item p,
.brand-item p {
  color: #666;
  font-size: 1rem;
  line-height: 1.5;
}

/* 商品列表样式 */
.product-list {
  width: 70%; /* 商品列表宽度 */
  text-align: right; /* 内容靠右对齐 */
}

.product {
  display: inline-block; /* 使商品块元素并排展示 */
  width: calc(100% - 20px); /* 根据需要调整宽度，留出间距 */
  margin: 10px 0;
}

/* 选择数量和按钮样式 */
.quantity-selection {
  margin: 10px 0;
  display: flex;
  justify-content: flex-end; /* 将内容靠右对齐 */
  align-items: center;
}

.adjust-button {
  padding: 5px 10px;
  border: none;
  border-radius: 5px;
  background-color: #3498db;
  color: white;
  cursor: pointer;
  margin: 0 5px; /* 按钮间距 */
}

.adjust-button:hover {
  background-color: #2980b9;
}

.quantity-input {
  width: 80px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  outline: none;
  text-align: center; /* 输入框文本居中 */
}

.quantity-input:focus {
  border-color: #3498db;
}

.button-group {
  display: flex; /* 将按钮组设置为 flexbox */
  margin-left: 10px; /* 为按钮组添加左边距 */
}

.buy-button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
  background-color: #e67e22; /* 修改加入购物车按钮颜色 */
  margin-left: 10px; /* 为立即购买按钮添加左边距 */
}

.buy-button:hover {
  background-color: #d95f21; /* 悬停时的颜色 */
}

.add-cart-button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
  background: linear-gradient(90deg, #ff6f00, #ff9f00); /* 渐变背景 */
}

.add-cart-button:hover {
  background: linear-gradient(90deg, #ff9f00, #ff6f00); /* 悬停时的渐变效果 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content {
    flex-direction: column;
  }
  .category-list,
  .product-list {
    width: 100%;
  }
}
</style>
